package cn.com.coldg.daoImpl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.com.coldg.bean.UserInfo;
import cn.com.coldg.dao.UserInfoDAO;
import cn.com.coldg.db.DatabaseConnection;

	
public class UserInfoDAOImpl implements UserInfoDAO{
	
	JdbcTemplate jdbc=new JdbcTemplate(DatabaseConnection.getDataSource());

	public boolean add(UserInfo user) {
	   String sql = "insert into userinfo(UserName," +
	 		"TeamId,Phone,Sex,Birthday,InseterTime)values(?,?,?,?,?,?)";
	   Object[] args=new Object[]{user.getUserName(),user.getTeamId(),user.getPhone(),user.getSex(),user.getBirthday(),user.getInseterTime()};
	   boolean flag=false;
	   int i=jdbc.update(sql, args);
	   if(i>0)
			flag=true;
	   return flag;
		
	}

	@SuppressWarnings("unchecked")
	public List<UserInfo> findAll() {
		String sql = "select UserId,UserName,TeamName,birthday,type,Phone,Sex,InseterTime from UserInfo a,UserTeam b where a.teamId = b.vid";
		List<UserInfo> list = jdbc.query(sql,new BeanPropertyRowMapper(UserInfo.class));
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<UserInfo> findByName(String name) {
		String sql = "select UserId,UserName,TeamName,Phone,Sex,InseterTime from UserInfo a,UserTeam b where a.teamId = b.vid and UserName like ?";
		Object[] args=new Object[]{"%"+name+"%"};
		List <UserInfo> user=(List<UserInfo>)jdbc.query(sql, args, new BeanPropertyRowMapper(UserInfo.class));
		if(user.size()>0){
			return user;
		}else{
			return null;
		}
	}

	public boolean update(UserInfo user) {
		String sql="update UserInfo  set UserName=?,birthday=?,TeamId=?,Phone=?,Sex=? where userId=?";
		Object[] args=new Object[]{user.getUserName(),user.getBirthday(),user.getTeamId(),user.getPhone(),user.getSex(),user.getUserId()};
		boolean flag=false;
		int count=jdbc.update(sql, args);
		if(count>0)
			flag=true;
		return flag;
			
	}


	public boolean delete(int userId) {
		String sql="delete from userinfo where userid=?";
		Object[] args = new Object[]{userId};
		boolean flag=false;
		int count=jdbc.update(sql, args);
		if(count>0)
			flag=true;
		return flag;
	}

	public UserInfo findById(int id) {
		String sql = "select UserId,UserName,birthday,TeamId,Phone,Sex,InseterTime from UserInfo  where UserId = ?";
		Object[] args=new Object[]{id};
		UserInfo user=(UserInfo)jdbc.queryForObject(sql, args, new BeanPropertyRowMapper(UserInfo.class));
			return user;
	}

	public void updateUserType() {
		String sql ="{call pro_customer()}";
		try {
			jdbc.getDataSource().getConnection().prepareCall(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
